;(function ($,window,document){

    var defaults = {
        title:'请选择设备',
        root:null,//根路径
        keyId:null,
        keyType:null,
        type:null,
        callback:function(){}   //回调
    };



    this.Event = function (element,options){
        var opts = options;
        $obj = $(element);


        this.Validator = function(){
            $("#event-form").bootstrapValidator({
                excluded: [':disabled', ':hidden', ':not(:visible)'],
                live: 'enabled',
                message: '非有效值',
                fields: {
                    eventTitle: {
                        validators: {
                            notEmpty: {
                                message: '事件标题不能为空'
                            }
                        }
                    },
                    eventContent: {
                        validators: {
                            notEmpty: {
                                message: '事件内容不能为空'
                            }
                        }
                    },
                    eventDateTime:{
                        validators: {
                            notEmpty: {
                                message: '事件发送时间不能为空'
                            },
                            date: {
                                format: 'YYYY-MM-DD HH:MM',
                                message: '格式为YYYY-MM-DD HH:mm'
                            }
                        }
                    }
                }
            });
        }


        this.filling = function(opts,obj){
            $obj.iziModal({
                title: '添加事件',
                headerColor: '#00c0ef',
                theme: '',  // light
                attached: '', // bottom, top
                icon: null,
                iconText: null,
                iconColor: '',
                rtl: false,
                width: 800,
                padding: 0,
                rtl: false,
                zindex: 1042,
                iframe: false,
                iframeHeight: 400,
                iframeURL: null,
                focusInput: false,
                group: '',
                loop: false,
                navigateCaption: true,
                navigateArrows: true, // closeToModal, closeScreenEdge
                history: true,
                restoreDefaultContent: false,
                autoOpen: true, // Boolean, Number
                bodyOverflow: false,
                fullscreen: true,
                openFullscreen: false,
                closeOnEscape: true,
                overlay: true,
                overlayClose: false,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                timeout: false,
                timeoutProgressbar: false,
                pauseOnHover: false,
                timeoutProgressbarColor: 'rgba(255,255,255,0.5)',
                transitionIn: 'comingIn',
                transitionOut: 'comingOut',
                transitionInOverlay: 'fadeIn',
                transitionOutOverlay: 'fadeOut',
                onFullscreen: function(){},
                onResize: function(){},
                onOpening: function(){},
                onOpened: function(){
                    obj.Validator();
                },
                onClosing: function(){
                    $('#event-form')[0].reset();
                    $("#event-form").data('bootstrapValidator').destroy();
                },
                onClosed: function(){}
            });
            var html = '<div class="box-body">'
                +'<form id="event-form" class="form-horizontal" method="post" enctype="multipart/form-data">'
                +' <input type="hidden" name="keyId" value="">'
                +'<input type="hidden" name="fileIds" value="">'
                +'<input type="hidden" name="keyType" value="1405">'
                +'<input type="hidden" name="type" value="event">'
                +'<div class="col-md-12">'
                +'<label  class="col-sm-3 control-label text-muted">事件标题<span class="text-red">*</span></label>'
                +'<div class="col-md-8 form-group" >'
                +'<input  class="form-control" name="eventTitle"/>'
                +'</div>'
                +'</div>'
                +'<div class="col-md-12">'
                +'<label  class="col-sm-3 control-label text-muted">事件发生时间<span class="text-red">*</span></label>'
                +'<div class="col-md-8 form-group" >'
                +'<input  class="form-control" name="eventDateTime"/>'
                +'</div>'
                +'</div>'

                +'<div class="col-md-12">'
                +'<label  class="col-sm-3 control-label text-muted">事件内容<span class="text-red">*</span></label>'
                +'<div class="col-md-8 form-group" >'
                +'<textarea class="form-control" name="eventContent"></textarea>'
                +'</div>'
                +'</div>'

                +'<div class="col-md-12">'
                +'<label  class="col-sm-3 control-label text-muted">文件</label>'
                +'<div class="col-md-8 form-group" >'
                +'<input type="file" name="files" id="files" class="file" multiple/>'
                +'</div>'
                +'</div>'
                +'</form>'
                +'</div>'
                +'<div class="box-footer">'
                +'<span class="pull-right">'
                +'<button data-iziModal-close class="btn btn-default" style="margin-right: 5px">关闭</button>'
                +'</span>'
                +'<span class="pull-right">'
                +'<button  class="btn btn-info" name="saveEvent" style="margin-right: 5px">提交</button>'
                +'</span>'
                +'</div>';

            $obj.find(".iziModal-content").html(html);
            if(opts.keyId!=null){
                $obj.find('input[name="keyId"]').val(opts.keyId);
            }


            if(opts.type!=null){
                $obj.find('input[name="type"]').val(opts.type);
            }

            $obj.find('input[name="type"]').val(opts.type);
            $obj.find("input[name='eventDateTime']").datetimepicker({
                autoclose: true,
                todayHighlight: true,
                language: 'zh-CN',
                minuteStep:1,
                todayBtn: true
            }).on('hide',function(e) {
                $('#event-form').data('bootstrapValidator')
                    .updateStatus('eventDateTime', 'NOT_VALIDATED',null)
                    .validateField('eventDateTime');
            });

            $obj.find('[name="files"]').fileinput({
                language: 'zh', //设置语言
                enctype: 'multipart/form-data',
                showUpload: false, //是否显示上传按钮
                showCaption: false,//是否显示标题
                browseClass: "btn btn-info", //按钮样式
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
            });



            this.eventBind = function(){
                var self = this;
                //必须先解绑再绑定事件，否则多次执行后会多次触发
                $obj.off('click','button[name="saveEvent"]').on('click','button[name="saveEvent"]',function(){
                    $('#event-form').bootstrapValidator('validate');
                    if($('#event-form').data('bootstrapValidator').isValid()){
                        isFileUpload(("#event-form"),function (data){
                            var str = "";
                            if(data != null && data.length > 0){
                                $.each(data,function (index,item){
                                    str+=item.fileId+",";
                                })
                            }
                            if(str != ""){
                                str = str.substring(0,str.length-1);
                            }
                            $obj.find('input[name="keyType"]').val(opts.keyType);
                            $obj.find("[name='fileIds']").val(str);
                            $obj.find("[name='type']").val("");
                            publicAjax(opts.root+"/event/addEventForWeChat","POST",$("#event-form"),function (data){
                                if(data.ret == 200){
                                    flavrShowByTime(data.msg,null,"success",false);
                                    $obj.iziModal("close",this);
                                }else{
                                    flavrShowByTime(data.msg,null,"danger",false);
                                }
                            });
                        });
                    }

                });
            }
        }

        this.init = function (){
            this.filling(opts,this);
            this.eventBind();
        }
        this.init();
    }
    $.fn.eventData = function(parameter,callback){
        if(typeof parameter == 'function'){//重载
            callback = parameter;
            parameter = {};
        }else{
            parameter = parameter || {};
            callback = callback || function(){};
        }
        var options = $.extend({},defaults,parameter);
        callback(new Event(this, options));
    };

})(jQuery, window,document);